/**
 * 
 * @authors youzhao.zhou@pandauu.com
 * @date    2016-09-21 12:45:33
 * @version $Id$
 * 依赖于DOM操作库
 * 发送信息模块实现：
 *          1. 文字发送按钮功能
 *                输入框有文字时显示发送按钮，没有文字时隐藏按钮
 *                将文字信息发送到后台
 *                对URL特殊处理
 * 
 *          2. 发送图片功能
 *                利用H5的fileReader功能将图片保存base64
 *                通过formData功能将图片上传到后台服务器
 *                
 * 
 */

;(function(root,factory){

  if(typeof exports === 'object' && typeof module === 'object'){
    
    factory(exports,typeof exports !== 'undefined' ? require('./zepto.js')&&root.$ : root.$, require('../../public_src/js/1_self/3_log.js'), require('../../public_src/js/1_self/2_config.js'), typeof exports !== 'undefined' ? require('../../public_src/js/underscore/underscore.js') : root._);

  } else if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['exports', './zepto.js', '../../public_src/js/1_self/3_log.js', '../../public_src/js/1_self/2_config.js', '../../public_src/js/underscore/underscore.js'], factory);
  } else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
    // CommonJS
    factory(exports, typeof exports !== 'undefined' ? require('./zepto.js')&&root.$ : root.$, require('../../public_src/js/1_self/3_log.js'), require('../../public_src/js/1_self/2_config.js'), typeof exports !== 'undefined' ? require('../../public_src/js/underscore/underscore.js') : root._);
  } else {
    // Browser globals
    factory({}, root.$, root.log, root.conf, root._);
  }
})(typeof window !== 'undefined' ? window : this ,function(exports, $, log, conf, _, undefined){
  'use strict';

  /*
    调试开关
  */
  log._logToggle(true);

  log._log(conf);
  var urlConf = conf._conf;

  /*
    发送按钮显示事件
    sendMsgBtnWidth 中 100 为发送按钮的宽度， 750 为设计图宽度
  
  */
  var sendMsgBtnWidth = 100/750;

  $('.jsSendInput').bind('input', function(event) {
    /* Act on the event */
    if ($(this).val()) {
      if ($('.jsSendBtn').hasClass('s-hide')) {
        $(this).css({width : ($(this).width()-sendMsgBtnWidth*parseFloat($('html').css('fontSize'))) / parseFloat($('html').css('fontSize')) + 'rem'});

        $('.jsSendBtn').removeClass('s-hide');
        $('.jsSendBtn').css({
          width: sendMsgBtnWidth + 'rem'
        });
      }
    }else{
      $(this).css({width : ($(this).width()+sendMsgBtnWidth*parseFloat($('html').css('fontSize'))) / parseFloat($('html').css('fontSize')) + 'rem'});

      $('.jsSendBtn').addClass('s-hide');
    }
    

  });

  $('.jsSendMsg').on('click', function(event) {
    

    /*
      事件委托
        根据HTML data-event属性判断哪个节点触发事件
        值：
          input   ---   input框触发事件
          img     ---   图片上传按钮
          msg     ---   发送信息
    */

    /* Act on the event */
    var target = $(event.target);
    var eventTarget = $(event.target).data('event');

    switch(eventTarget){
      case 'img':
        $(event.target).unbind('change').bind('change', function(e) {
          /* Act on the event */
          if (typeof FileReader === 'undefined'||typeof FormData === 'undefined') {
            alert('您的浏览器暂不支持图片上传，请更换浏览器！');

            return false;
          }

          var self = this;

          var imgForm = new FormData();

          imgForm.append('imageFile',self.files[0]);

          imgAjax({
            url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.upload,
            type: 'POST',
            data: imgForm,
            success: function(data){
              log._log(data);

              if (data.code === 0) {
                sendImgInfo(data.path);
                
              }else{
                $('#fail').removeClass('s-hide');
                $('.js-warn-content').html(data.msg);
                addCloseEvent('.js-fail');
                log._log(data.msg);
              }
            },
            error: function(error){
              log._log(error);
            }
          });
          
        });
        break;
      case 'msg':
        event.preventDefault();

        sendMsg(
          {
            type: 1,
            content: $('.jsSendInput').val(),
            thread_id: $('.jsRemark').data('id')
          },
          function(data){
            if (data.code === 0 ) {
              // $('#fail').removeClass('s-hide');
              // $('.js-warn-content').html(data.msg);
              // addCloseEvent('.js-fail');

              $('.jsSendInput').val('');
              $('.jsSendInput').trigger('input');


              if (data.data.type === '2') {
                data.data.msg = urlConf.root + data.data.msg;
                data.data.thumb = data.data.msg.replace('uploads/kf/','uploads/kf/thumbnail/');
              }
              var tempData = [];
              tempData.push(data.data);
              log._log(tempData);
              renderMsg(_, tempData);
            }else{
              $('#fail').removeClass('s-hide');
              $('.js-warn-content').html(data.msg);
              addCloseEvent('.js-fail');
            }

          },
          function (data){
            $('#fail').removeClass('s-hide');
            $('.js-warn-content').html('网络连接错误！');
            addCloseEvent('.js-fail');
          }
        );

        break;
      case 'label':
          
        window.location.href = './label.php?thread_id=' + $('.jsRemark').data('id');

        break;
    }
  });
  /*
    上传图片后发送信息到服务器
  */

  function sendImgInfo(dataImg){

    sendMsg(
      {
        type: 2,
        content: dataImg,
        thread_id: $('.jsRemark').data('id')
      },
      function(data){
        if (data.code === 0 ) {
          if(!$('.msg img').attr('src')){
            $('.msg img').attr('src',dataImg);
          }

          if (data.data.type === '1') {
            data.data.msg = setUrl(data.data.msg);
          }else{
            data.data.msg = urlConf.root + data.data.msg;
            data.data.thumb = data.data.msg.replace('uploads/kf/','uploads/kf/thumbnail/');
          }
          var tempData = [];
          tempData.push(data.data);
          log._log(tempData);
          renderMsg(_, tempData);

          imgDefer();
          
          $(self).val('');

        }else{
          $('#fail').removeClass('s-hide');
          $('.js-warn-content').html(data.msg);
          addCloseEvent('.js-fail');
        }
      },
      function (data){
        $('#fail').removeClass('s-hide');
        $('.js-warn-content').html('网络连接错误！');
        addCloseEvent('.js-fail');
      }
    );
    
  }
  /*
    发送消息请求
  */
  function sendMsg(data, success, fail){
    $.ajax({
      url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.addMemo,
      type: 'POST',
      dataType: 'json',
      data: data,
    })
    .done(function(data) {
      
      if (typeof success === 'function') {
        success(data);
      }
    })
    .fail(function() {
      if (typeof fail === 'function') {
        fail(data);
      }
    })
    .always(function() {
      log._log("complete");
    });
  }
  /*
    启动弹框关闭按钮
  */
  function addCloseEvent(selector){
    $(selector).unbind('click').bind('click', function(event) {
      /* Act on the event */
      $($(this).data('target')).addClass('s-hide');

      $(selector).unbind('click');
    });
  }
  /*
    H5图片上传
  */
  function imgAjax(options){

    var oReq = new XMLHttpRequest();
    oReq.open(options.type||'', options.url||'');
    oReq.send(options.data||'');

    oReq.onload = function(data){
      log._log(this);
      if (this.readyState===4 && this.status===200) {
        log._log(data);
        if (typeof options.success === 'function') {
          options.success(JSON.parse(data.target.response));
        }
      }else{
        if (typeof options.error === 'function') {
          options.error(data.target.response);
        }
      }
    };
  }
  /*
    渲染消息
  
  */
  function renderMsg(_, data){
    var tpl = $('#remarkTpl');
    log._log(data);
    $('.jsRemarkUl').append(_.template(tpl.html())({list: data}));

    $('body')[0].scrollTop = $('.jsRemark').height()-$(window).height();
  }

  /*
    图片延时加载
  */

  function imgDefer(){
    var isDeferr = $('[data-deferr]').data('deferr');
    var doms = $('[data-deferr]');

    doms.each(function(index, el) {
      if (isDeferr != 1) {
        return false;
      }
      var self = this;
      var imgUrl = urlConf.root + $(self).data('url');

      var img = new Image();

        img.onload = function(){
          $(self).attr({
            src : imgUrl
          });
          
        };

        img.src = imgUrl;
    });

  }

});